package ${package}.rss.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import ${package}.rss.model.RssEntry;

/**
 *Searched Keyword DAO, springJdbcTemplate implementation
 * 
 * @author Ke CAI
 */
public class RssEntryJDBCDAO extends JdbcDaoSupport implements IRssEntryDAO {
	// Row -> Bean property mapper
	class RssEntryRowMapper implements RowMapper {

		public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
			RssEntry entry = new RssEntry();
			entry.setSourceName(rs.getString("SOURCENAME"));
			entry.setUrl(rs.getString("URL"));
			entry.setUrlForIndex(rs.getString("URLFORINDEX"));
			entry.setTitle(rs.getString("TITLE"));
			entry.setDescription(rs.getString("DESCRIPTION"));
			entry.setPublishDate(rs.getDate("PUBLISHDATE"));
			entry.setCategory(rs.getString("CATEGORY"));

			return entry;
		}

	}

	public List<RssEntry> getRssEntries(int offset, int size) {
		String sqlString = "SELECT SOURCENAME,URL,TITLE,URLFORINDEX,DESCRIPTION,PUBLISHDATE,CATEGORY FROM RSSENTRY LIMIT "
				+ offset + ", " + size;
		return getJdbcTemplate().query(sqlString, new RssEntryRowMapper());
	}

	public void saveRssEntries(List<RssEntry> entries) {
		String sql = "INSERT INTO RSSENTRY (SOURCENAME,URL,TITLE,URLFORINDEX,DESCRIPTION,PUBLISHDATE,CATEGORY) VALUES (?,?,?,?,?,?,?)";
		SimpleJdbcTemplate simpleJdbcTemplate = new SimpleJdbcTemplate(
				getDataSource());
		List<Object[]> batch = new ArrayList<Object[]>();
		Date lastInsertDate = getLatestInsertDate();
		for (RssEntry rssEntry : entries) {
			Date publishDate = rssEntry.getPublishDate();
			if ((lastInsertDate == null)
					|| (publishDate != null && publishDate
							.after(lastInsertDate))) {
				Object[] values = new Object[] { rssEntry.getSourceName(),
						rssEntry.getUrl(), rssEntry.getTitle(),
						rssEntry.getUrlForIndex(), rssEntry.getDescription(),
						rssEntry.getPublishDate(), rssEntry.getCategory() };
				batch.add(values);
			}
		}

		simpleJdbcTemplate.batchUpdate(sql, batch);
	}

	public int getRssEntriesCount() {
		String sql = "SELECT COUNT(*) FROM RSSENTRY";
		return getJdbcTemplate().queryForInt(sql);
	}

	private Date getLatestInsertDate() {
		String sql = "SELECT MAX(PUBLISHDATE) FROM RSSENTRY";
		return (Date) getJdbcTemplate().queryForObject(sql, Date.class);
	}
}